﻿using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Jinndev.UI;
using UnityEngine.EventSystems;
using System;
using System.IO;
using System.Text;
using Jinndev.Json;

namespace Jinndev {

    public class MapEditorUI : BaseUIBehaviour, IEscape {

        #region static
        public static readonly string PATH = "Prefab/UI/MapEditor/MapEditorUI";

        public static MapEditorUI Instance { get; private set; }

        public static MapEditorUI Create(string filePath) {
            var com = UIManager.Instance.Add<MapEditorUI>(PATH, UIParam.FullScreen);
            com.Init(filePath);
            return com;
        }
        #endregion

        public const int MAX_LAYER = 10;
        
        /// <summary>每一层的描述</summary>
        public static readonly string[] LAYER_DESC = new string[] { 
            "地面",
            "底层周边",
            "家具",
            "家具",
            "家具",
            "家具",
            "外层墙体",
            "覆盖墙面",
            "外层墙体",
            "外层周边"
        };

        [Header("部分")]
        public GameObject tileToolPart;
        public GameObject tileViewPart;

        [Header("网格")]
        public RectTransform gridLayer;
        public RectTransform layerContainer;
        public Material gridMaterial;

        [Header("背景颜色")]
        public Image imageBgColor;
        [Header("网格颜色")]
        public Image imageGridColor;
        [Header("网格角度")]
        public InputField inputAngle;
        public Slider sliderAngle;
        [Header("网格长度")]
        public InputField inputLength;
        public Slider sliderLength;
        [Header("网格数量")]
        public InputField inputSizeX;
        public Slider sliderSizeX;
        public InputField inputSizeY;
        public Slider sliderSizeY;
        [Header("缩放")]
        public InputField inputScale;
        public Slider sliderScale;
        [Header("层级")]
        public GameObject toggleLayerPrefab;


        [Header("瓦片")]
        public InputField inputSearch;
        public GridView tileView;
        public GameObject tileItemPrefab;
        public MapBuildTilePanel buildTilePanel;
        public MapCurObjPanel curObjPanel;

        [Header("其他")]
        public Text textFile;
        public DragHelper dragHelper;
        public ZoomHelper zoomHelper;
        public PointerClickHelper clickHelper;
        public Text textTip;

        [Header("选中的瓦片")]
        public RectTransform selectTile;
        private Int2 selectTileIndex = new Int2(); // 选中瓦片的坐标

        private string filePath;
        private MapData mapData;

        private MapGridRenderer gridRenderer;
        private Vector2 centerOffset;
        private MapLayerUI[] layers;
        private Vector2 gridSize = new Vector2();

        private Camera bgCamera;    // 背景颜色摄像机
        private Color bgColor;      // 关闭后还原摄像机背景颜色

        private List<TileConfig> tileConfigList = new List<TileConfig>();
        private int selectedTileIndex = -1;
        private TileConfig selectedTileConfig; // 移动模式下，可能目标不在列表内，所以selectedTileIndex为-1
        private int activeLayerIndex = 0;

        private Toggle firstLayerToggle = null;
        private PointerEventData pointerEventData;
        private MapTileObjUI hoverTileObj;

        public int ActiveLayerIndex => activeLayerIndex;
        public MapLayerData ActiveMapLayerData => activeLayerIndex < MAX_LAYER ? mapData.layers[activeLayerIndex] : null;
        public MapData MapData => mapData;
        public MapLayerUI[] Layers => layers;

        private void Awake() {
            Instance = this;

            pointerEventData = new PointerEventData(EventSystem.current);

            bgCamera = Camera.main;
            bgColor = bgCamera.backgroundColor;

            // 创建网格渲染器，挂载指定摄像机上
            gridRenderer = Camera.main.gameObject.AddComponent<MapGridRenderer>();
            gridRenderer.material = new Material(gridMaterial);

            // 背景颜色
            if (!string.IsNullOrWhiteSpace(Setting.Instance.mapBgColor)) {
                bgCamera.backgroundColor = CommonUtil.ColorHexToColor(Setting.Instance.mapBgColor);
            }
            imageBgColor.color = bgCamera.backgroundColor;

            // 网格颜色
            if (!string.IsNullOrWhiteSpace(Setting.Instance.mapGridColor)) {
                gridRenderer.material.color = CommonUtil.ColorHexToColor(Setting.Instance.mapGridColor);
            }
            imageGridColor.color = gridRenderer.material.color;

            // 角度
            inputAngle.SetTextWithoutNotify(gridRenderer.angle.ToString());
            inputAngle.onValueChanged.AddListener(text => {
                float.TryParse(text, out gridRenderer.angle);
                mapData.angle = gridRenderer.angle;
                CalculateGridSize();
                sliderAngle.SetValueWithoutNotify(gridRenderer.angle);
            });

            sliderAngle.SetValueWithoutNotify(gridRenderer.angle);
            sliderAngle.onValueChanged.AddListener(value => {
                gridRenderer.angle = value;
                mapData.angle = gridRenderer.angle;
                CalculateGridSize();
                inputAngle.SetTextWithoutNotify(gridRenderer.angle.ToString());
            });

            UIUtil.AddButtonClick(inputAngle, "Button Reset", () => sliderAngle.value = MapGridRenderer.DefalutAngle);

            // 长度
            inputLength.SetTextWithoutNotify(gridRenderer.length.ToString());
            inputLength.onValueChanged.AddListener(text => {
                float.TryParse(text, out gridRenderer.length);
                mapData.length = gridRenderer.length;
                CalculateGridSize();
                sliderLength.SetValueWithoutNotify(gridRenderer.length);
            });

            sliderLength.SetValueWithoutNotify(gridRenderer.length);
            sliderLength.onValueChanged.AddListener(value => {
                gridRenderer.length = value;
                mapData.length = gridRenderer.length;
                CalculateGridSize();
                inputLength.SetTextWithoutNotify(gridRenderer.length.ToString());
            });

            UIUtil.AddButtonClick(inputLength, "Button Reset", () => sliderLength.value = MapGridRenderer.DefalutLength);

            // 数量
            // X
            inputSizeX.SetTextWithoutNotify(gridRenderer.sizeX.ToString());
            inputSizeX.onValueChanged.AddListener(text => {
                sliderSizeX.SetValueWithoutNotify(gridRenderer.sizeX);
                int.TryParse(text, out gridRenderer.sizeX);
                mapData.size.x = gridRenderer.sizeX;
            });

            sliderSizeX.SetValueWithoutNotify(gridRenderer.sizeX);
            sliderSizeX.onValueChanged.AddListener(value => {
                gridRenderer.sizeX = (int)value;
                mapData.size.x = gridRenderer.sizeX;
                inputSizeX.SetTextWithoutNotify(gridRenderer.sizeX.ToString());
            });

            // Y
            inputSizeY.SetTextWithoutNotify(gridRenderer.sizeY.ToString());
            inputSizeY.onValueChanged.AddListener(text => {
                sliderSizeY.SetValueWithoutNotify(gridRenderer.sizeY);
                int.TryParse(text, out gridRenderer.sizeY);
                mapData.size.y = gridRenderer.sizeY;
            });

            sliderSizeY.SetValueWithoutNotify(gridRenderer.sizeY);
            sliderSizeY.onValueChanged.AddListener(value => {
                gridRenderer.sizeY = (int)value;
                mapData.size.y = gridRenderer.sizeY;
                inputSizeY.SetTextWithoutNotify(gridRenderer.sizeY.ToString());
            });

            UIUtil.AddButtonClick(inputSizeX, "Button Reset", () => sliderSizeX.value = MapGridRenderer.DefalutCount);
            UIUtil.AddButtonClick(inputSizeY, "Button Reset", () => sliderSizeY.value = MapGridRenderer.DefalutCount);
            CalculateGridSize();

            // 缩放
            inputScale.SetTextWithoutNotify(gridRenderer.scale.ToString());
            inputScale.onValueChanged.AddListener(text => {
                sliderScale.SetValueWithoutNotify(gridRenderer.scale);
                float.TryParse(text, out gridRenderer.scale);
                gridLayer.localScale = Vector3.one * gridRenderer.scale;
                zoomHelper.SetZoom(gridRenderer.scale);
            });

            sliderScale.SetValueWithoutNotify(gridRenderer.scale);
            sliderScale.onValueChanged.AddListener(value => {
                gridRenderer.scale = value;
                gridLayer.localScale = Vector3.one * gridRenderer.scale;
                zoomHelper.SetZoom(gridRenderer.scale);
                inputScale.SetTextWithoutNotify(gridRenderer.scale.ToString());
            });
            zoomHelper.minValue = sliderScale.minValue;
            zoomHelper.maxValue = sliderScale.maxValue;
            zoomHelper.sensitivity = Application.isEditor ? 15f : 1.5f;

            UIUtil.AddButtonClick(inputScale, "Button Reset", () => sliderScale.value = MapGridRenderer.DefalutScale);

            // 层级
            layers = new MapLayerUI[MAX_LAYER];
            // 创建渲染层
            for (int i = 0; i < MAX_LAYER; i++) {
                int index = i;

                // 创建层级
                GameObject layerObj = new GameObject("Layer" + index, new Type[] { typeof(RectTransform) });
                MapLayerUI layerUI = layerObj.AddComponent<MapLayerUI>(); ;
                layerUI.transform.SetParent(layerContainer, false);
                layerUI.layerIndex = i;
                layers[index] = layerUI;

                // 创建层级开关
                GameObject obj = Instantiate(toggleLayerPrefab);
                obj.transform.SetParent(toggleLayerPrefab.transform.parent);
                obj.transform.SetSiblingIndex(toggleLayerPrefab.transform.GetSiblingIndex());
                UIUtil.SetText(obj, "Label", $"层级{index + 1}-{LAYER_DESC[index]}");

                Toggle toggle = obj.GetComponent<Toggle>();
                toggle.onValueChanged.AddListener(isOn => OnToggleLayer(isOn, index));

                if (index == 0) {
                    firstLayerToggle = toggle;
                }
            }
            // 创建路径层
            {
                // 创建层级开关
                GameObject obj = Instantiate(toggleLayerPrefab);
                obj.transform.SetParent(toggleLayerPrefab.transform.parent);
                obj.transform.SetSiblingIndex(toggleLayerPrefab.transform.GetSiblingIndex());
                UIUtil.SetText(obj, "Label", $"路径层级");

                Toggle toggle = obj.GetComponent<Toggle>();
                toggle.onValueChanged.AddListener(isOn => OnToggleLayer(isOn, MAX_LAYER));
            }
            toggleLayerPrefab.SetActive(false);



            // 拖拽缩放功能
            dragHelper.onDrag += OnDrag;
            zoomHelper.SetZoom(1);
            zoomHelper.onZoom += OnZoom;
            clickHelper.onPointerClick += OnClick;

            // 瓦片列表
            tileView.onCreateItem = OnCreateTileItem;
            tileView.onUpdateItem = OnUpdateTileItem;

            buildTilePanel.onSelect = OnSelectTileRotation;
            buildTilePanel.onClose = ClearSelectedTile;

            curObjPanel.onSelect = OnSelectObj;
            curObjPanel.onClose = ClearSelectedObj;

            selectTile.gameObject.SetActive(false);

            RefreshTip();
        }

        private void Init(string filePath) {
            this.filePath = filePath;
            if (File.Exists(filePath)) {
                // 读取
                string text = File.ReadAllText(filePath, Encoding.UTF8);
                mapData = JsonUtil.Deserialize<MapData>(text);

                sliderAngle.value = mapData.angle;
                sliderLength.value = mapData.length;
                sliderSizeX.value = mapData.size.x;
                sliderSizeY.value = mapData.size.y;
            }
            else {
                // 创建
                mapData = new MapData();

                mapData.angle = gridRenderer.angle;
                mapData.length = gridRenderer.length;
                mapData.size = new Int2(gridRenderer.sizeX, gridRenderer.sizeY);
            }

            textFile.text = filePath;//.Substring(Setting.Instance.mapExportRootDir.Length);

            // 选中第一个，并触发事件
            if (!firstLayerToggle.isOn) {
                firstLayerToggle.isOn = true;
            }
            else {
                OnToggleLayer(true, 0);
            }
        }

        private void Start() {
            centerOffset = RectTransformUtility.CalculateRelativeRectTransformBounds(transform, gridLayer).center;
            gridRenderer.centerOffset += centerOffset;

            MapUtil.LoadTileConfig();
            ReloadTileList();

            LoadMapLayerTexture();
        }

        private void OnDestroy() {
            Instance = null;
            if (CommonUtil.IsQuitting) {
                return;
            }
            Destroy(gridRenderer);

            Setting.Instance.mapBgColor = CommonUtil.ColorToHex(bgCamera.backgroundColor);
            Setting.Instance.mapGridColor = CommonUtil.ColorToHex(gridRenderer.material.color);
            Setting.Save();

            bgCamera.backgroundColor = bgColor;
        }


        private void Update() {
            MapTileObjUI tileObj = null;

            if (selectTile.gameObject.activeSelf) {
                Int2 index = GetSnapIndex();
                if (selectTileIndex != index) {
                    selectTileIndex = index;
                    selectTile.anchoredPosition = GetTilePos(index);
                }
            }
            else {
                pointerEventData.position = Input.mousePosition;
                EventSystem.current.RaycastAll(pointerEventData, raycastResults);
                tileObj = GetActiveTile(raycastResults);
            }

            if (hoverTileObj != tileObj) {
                if (hoverTileObj != null) {
                    hoverTileObj.ToggleHover(false);
                }
                hoverTileObj = tileObj;
                if (hoverTileObj != null) {
                    hoverTileObj.ToggleHover(true);
                }
            }
        }

        /// <summary>
        /// 当网格角度、长度变化时，需重新计算网格大小
        /// </summary>
        private void CalculateGridSize() {
            // 一个菱形是4个gridSize，左右、上下各2个
            float length = gridRenderer.length;
            gridSize.x = length * Mathf.Cos(gridRenderer.angle * Mathf.Deg2Rad);
            gridSize.y = length * Mathf.Sin(gridRenderer.angle * Mathf.Deg2Rad);
        }

        public void OnClickBgColor() {
            var colorPicker = ColorPickerLayer.Create(color => {
                bgCamera.backgroundColor = color;
            });
            colorPicker.color = bgCamera.backgroundColor;
        }

        public void OnClickGridColor() {
            var colorPicker = ColorPickerLayer.Create(color => {
                gridRenderer.material.color = color;
                imageGridColor.color = color;
            });
            colorPicker.color = gridRenderer.material.color;
        }

        /// <summary> 拖拽事件 </summary>
        private void OnDrag(DragHelper helper, PointerEventData eventData, float deltaX, float deltaY) {
            gridRenderer.centerOffset.x -= deltaX;
            gridRenderer.centerOffset.y -= deltaY;
            gridLayer.Translate(-deltaX, -deltaY, 0);
        }

        /// <summary> 缩放事件 </summary>
        private void OnZoom(ZoomHelper helper, float value) {
            //targetScale = value;
            gridRenderer.scale = value;
            gridLayer.localScale = Vector3.one * value;

            inputScale.SetTextWithoutNotify(value.ToString());
            sliderScale.SetValueWithoutNotify(value);
        }

        private List<RaycastResult> raycastResults = new List<RaycastResult>();

        /// <summary> 点击事件 </summary>
        private void OnClick(PointerEventData eventData) {

            if (buildTilePanel.gameObject.activeSelf) {
                // 选中了要放置的瓦片类型时
                if (eventData.button == PointerEventData.InputButton.Left) {
                    // 放置
                    PlaceTileObj(selectedTileConfig);
                }
                else if (eventData.button == PointerEventData.InputButton.Right) {
                    // 取消选中
                    //ClearSelectedTile();
                    buildTilePanel.Hide();
                }
            }
            else if (curObjPanel.gameObject.activeSelf) {
                // 选中了地图中的物体时
                if (eventData.button == PointerEventData.InputButton.Left) {
                    if (hoverTileObj != null) {
                        // 如果悬浮在地图物体上，则选中地图中的物体
                        curObjPanel.Show(hoverTileObj);
                        buildTilePanel.Hide();
                    }
                }
                else if (eventData.button == PointerEventData.InputButton.Right) {
                    // 取消选中
                    curObjPanel.Hide();
                }
            }
            else {
                // 什么都没有选中时
                if (eventData.button == PointerEventData.InputButton.Left) {
                    if (hoverTileObj != null) {
                        // 如果悬浮在地图物体上，则选中地图中的物体
                        curObjPanel.Show(hoverTileObj);
                        buildTilePanel.Hide();
                    }
                }
                else if (eventData.button == PointerEventData.InputButton.Right) {
                    if (hoverTileObj != null) {
                        // 则移除场景中的物体
                        RemoveTileObj(hoverTileObj.data);
                    }
                }
            }


        }

        private void RefreshTip() {
            string color = "#00ff00";

            if (buildTilePanel.gameObject.activeSelf) {
                textTip.text = $"<color={color}>左</color>键放置，<color={color}>右</color>键取消，<color={color}>R</color>键转动";
            }
            else if (curObjPanel.gameObject.activeSelf) {
                textTip.text = $"<color={color}>左</color>键选中，<color={color}>右</color>键取消";
            }
            else {
                textTip.text = $"<color={color}>左</color>键选中，<color={color}>右</color>键移除";
            }
        }

        private MapTileObjUI GetActiveTile(List<RaycastResult> raycastResults) {
            foreach (var res in raycastResults) {
                if (res.gameObject.name.StartsWith(nameof(MapTileObjUI))) {
                    if (res.gameObject.transform.parent.GetComponent<MapLayerUI>().Active) {
                        return res.gameObject.GetComponent<MapTileObjUI>();
                    }
                }
            }
            return null;
        }

        /// <summary> 放置瓦片 </summary>
        private void PlaceTileObj(TileConfig tileConfig) {
            MapLayerData layerData = ActiveMapLayerData;
            if (layerData == null) {
                return;
            }
            MapLayerUI layerUI = layers[activeLayerIndex];

            var index = GetSnapIndex();

            var tileData = new MapObjData(tileConfig, index, buildTilePanel.Rotation);
            int insertIndex = layerUI.AddTile(tileData, true);
            if (insertIndex != -1) {
                layerData.dataList.Insert(insertIndex, tileData);

                // 删除原始瓦片
                if (srcMoveTileData != null) {
                    tileData.slot = srcMoveTileData.slot;
                    RemoveTileObj(srcMoveTileData);
                    EventManager.Invoke(CustomEvent.ChangeObjSlot);
                    srcMoveTileData = null;
                    buildTilePanel.Hide();
                }
            }
            else {
                NotificationUI.Create("位置已经占用", LogType.Error);
            }
        }

        private void RemoveTileObj(MapObjData tileData) {
            MapLayerData layerData = mapData.layers[activeLayerIndex];
            MapLayerUI layerUI = layers[activeLayerIndex];

            if (layerUI.RemoveTile(tileData)) {
                layerData.dataList.Remove(tileData);
            }
            else {
                NotificationUI.Create("移除失败", LogType.Error);
            }
        }

        /// <summary>
        /// 获得指针附近的吸附坐标
        /// </summary>
        public Vector2 GetTilePos(Int2 index) {
            return new Vector2(gridSize.x * index.x, gridSize.y * index.y);
        }

        /// <summary>
        /// 获得指针附近的吸附坐标索引值
        /// </summary>
        private Int2 GetSnapIndex() {
            Vector2 position = UIManager.Instance.ScreenToAnchoredPosition(Input.mousePosition) - centerOffset - gridLayer.anchoredPosition;
            position /= gridRenderer.scale;

            int x = Mathf.RoundToInt(position.x / gridSize.x);
            int y = Mathf.RoundToInt(position.y / gridSize.y);
            return new Int2(x, y);
        }

        private void ReloadTileList() {
            MapUtil.ReloadTileConfigList(tileConfigList, inputSearch.text);
            tileView.Reload(tileConfigList.Count);
        }

        private GameObject OnCreateTileItem() {
            GameObject obj = Instantiate(tileItemPrefab);
            var item = obj.GetComponent<MapTileItemUI>();
            item.onClick = OnClickTileItem;
            return obj;
        }

        private void OnUpdateTileItem(GameObject obj, int index) {
            var item = obj.GetComponent<MapTileItemUI>();
            item.Refresh(tileConfigList[index], index, index == selectedTileIndex);
        }

        /// <summary> 点击瓦片列表中的一项 </summary>
        private void OnClickTileItem(MapTileItemUI item) {
            ClearSelectedTile();

            selectedTileIndex = item.index;
            selectedTileConfig = tileConfigList[selectedTileIndex];

            item.Selected = true;
            srcMoveTileData = null;
            buildTilePanel.Show(selectedTileConfig);
            curObjPanel.Hide();
            RefreshLayerAlpha();
        }


        /// <summary>移动时，记录原始瓦片，确认移动后需删除原始瓦片</summary>
        private MapObjData srcMoveTileData;

        /// <summary> 移动场景中的瓦片 </summary>
        public void MoveTile(MapObjData data) {
            // 找到对应的TileConfig
            int index = -1;
            if (MapUtil.tileConfigs.TryGetValue(data.id, out selectedTileConfig)) {

            }

            if (selectedTileConfig == null) {
                NotificationUI.Create("未找到瓦片配置: " + data.id);
                return;
            }

            ClearSelectedTile();

            // 记录原始瓦片，确认移动后需删除原始瓦片
            srcMoveTileData = data;

            buildTilePanel.Show(selectedTileConfig, data.rotation);
            curObjPanel.Hide();
            RefreshLayerAlpha();

            GameObject obj = tileView.GetItem(index);
            if (obj != null) {
                obj.GetComponent<MapTileItemUI>().Selected = true;
            }
        }

        /// <summary> 选中了一个方向的瓦片 </summary>
        private void OnSelectTileRotation(Texture texture, float scaleX, TileConfig config) {
            selectTile.gameObject.SetActive(true);
            selectTile.GetComponent<RawImage>().texture = texture;
            selectTile.localScale = new Vector3(scaleX, 1, 1);
            selectTile.sizeDelta = new Vector2(texture.width, texture.height);
            selectTile.pivot = config.anchor;
            //selectTile.pivot = new Vector2(1 - config.anchor.x, config.anchor.y);
            RefreshTip();
        }

        /// <summary> 清除选中的瓦片 </summary>
        private void ClearSelectedTile() {
            if (selectedTileIndex != -1) {
                GameObject obj = tileView.GetItem(selectedTileIndex);
                if (obj != null) {
                    obj.GetComponent<MapTileItemUI>().Selected = false;
                }
            }
            selectedTileIndex = -1;
            srcMoveTileData = null;
            RefreshLayerAlpha();
            selectTile.gameObject.SetActive(false);
            RefreshTip();
        }

        private void OnSelectObj(MapTileObjUI tileObj) {
            RefreshTip();
        }

        private void ClearSelectedObj() {
            RefreshTip();
        }



        public override void Destroy() {
            DialogUI.CreateConfirm("退出", "是否保存修改?", () => {
                // yes
                OnClickSave();
                Destroy(gameObject);
            }, () => {
                // no
                Destroy(gameObject);
            }, () => {
                // close
            });
        }

        public EscapeResult OnEscape() {
            Destroy();
            return EscapeResult.Cancel;
        }

        public void OnClickSave() {
            var setting = new Newtonsoft.Json.JsonSerializerSettings();
            setting.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

            // 按显示顺序排序
            for (int i = 0; i < layers.Length; i++) {
                MapLayerData layerData = mapData.layers[i];
                MapLayerUI layer = layers[i];
                layerData.dataList.Sort((a, b) => {
                    var tileA = layer.tiles[a.index];
                    var tileB = layer.tiles[b.index];
                    return tileA.transform.GetSiblingIndex().CompareTo(tileB.transform.GetSiblingIndex());
                });
            }

            //for (int l = 0; l < layers.Length; l++) {
            //    MapLayerUI layer = layers[l];
            //    MapLayerData layerData = mapData.layers[l];
            //    layerData.dataList.Clear();

            //    int count = layer.transform.childCount;

            //    for (int i = 0; i < count; i++) {
            //        Transform child = layer.transform.GetChild(i);
            //        MapTileObjUI tile = child.GetComponent<MapTileObjUI>();
            //        if (tile != null) {
            //            layerData.dataList.Add(tile.data);
            //        }
            //    }
            //}

            string text = JsonUtil.Serialize(mapData, setting);
            File.WriteAllText(filePath, text, Encoding.UTF8);
            NotificationUI.Create("保存完成");
        }

        public void OnClickSearch() {
            ReloadTileList();
        }

        public void OnClickClearSearch() {
            inputSearch.text = "";
            OnClickSearch();
        }

        private void PrepareLayerData() {
            if (mapData.layers == null) {
                mapData.layers = new List<MapLayerData>(MAX_LAYER);
                for (int i = 0; i < MAX_LAYER; i++) {
                    mapData.layers.Add(new MapLayerData());
                }
            }
            else if (mapData.layers.Count < MAX_LAYER) {
                int delta = MAX_LAYER - mapData.layers.Count;

                for (int i = 0; i < delta; i++) {
                    mapData.layers.Add(new MapLayerData());
                }
            }
        }

        private void OnToggleLayer(bool isOn, int index) {
            if (!isOn) {
                return;
            }
            activeLayerIndex = index;

            PrepareLayerData();
            for (int i = 0; i < layers.Length; i++) {
                layers[i].Active = i == index;
            }
            RefreshLayerAlpha();
            if (index < MAX_LAYER) {
                layers[index].Flash();
            }
            EventManager.Invoke(CustomEvent.ChangeActiveLayer);

            if (activeLayerIndex == MAX_LAYER) {
                buildTilePanel.Hide();
                curObjPanel.Hide();
            }
            tileToolPart.SetActive(activeLayerIndex < MAX_LAYER);
            tileViewPart.SetActive(activeLayerIndex < MAX_LAYER);
        }

        private void RefreshLayerAlpha() {
            for (int i = 0; i < layers.Length; i++) {
                layers[i].RefreshAlpha(activeLayerIndex == MAX_LAYER);
            }
        }

        /// <summary>
        /// 加载层级图片
        /// </summary>
        private void LoadMapLayerTexture() {
            PrepareLayerData();

            for (int i = 0; i < layers.Length; i++) {
                MapLayerData layerData = mapData.layers[i];
                MapLayerUI layerUI = layers[i];

                foreach (var data in layerData.dataList) {
                    layerUI.AddTile(data, false);
                }
            }
        }




    }

}
